package de.tudarmstadt.gdi1.project.analyse;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Random;

import de.tudarmstadt.gdi1.project.Charset;
import de.tudarmstadt.gdi1.project.alphabet.Alphabet;
import de.tudarmstadt.gdi1.project.substitution.CipherUtils;
import de.tudarmstadt.gdi1.project.substitution.mono.Monoalphabetic;

public abstract class MonoalphabeticAnalyse {

	protected CipherUtils u = new CipherUtils();
	protected int counter = 0;
	protected Monoalphabetic decode;

	public int[] matches(Alphabet key, char[] reconKey) {
		int[] a = new int[key.size()];
		for (int i = 0; i < reconKey.length; i++) {
			if (reconKey[i] == key.getChar(i)) {
				a[i] = 1;
			} else
				a[i] = 0;
		}
		return a;
	}

	public int corrects(Alphabet source, Alphabet key, char[] reconKey,
			String path) {
		int v = 0;
		int[] a = matches(key, reconKey);
		boolean check = true;
		if (path != null) {
			for (int i = 0; i < path.length(); i++) {
				if ((a[source.getIndex(path.charAt(i))] == 1) && check) {
					v++;
				} else
					check = false;
			}
		} else {
			for (int i : a) {
				v += i;
			}
		}
		return v;
	}
	
	public Alphabet formAlphabet(Map<Character, Character> current,
			Alphabet alphabet) {
		Random random = new Random();
		ArrayList<Character> full = new ArrayList<Character>(alphabet.size());
		Character[] array = new Character[alphabet.size()];
		for (char a : alphabet) {
			if (current.containsKey(a)) {
				array[alphabet.getIndex(a)] = current.get(a);
			}
		}
		for (int i = 0; i < array.length; i++) {
			if (array[i] == null) {
				while (true) {
					char c = alphabet.getChar(random.nextInt(alphabet.size()-1));
					if (!Arrays.asList(array).contains(c)) {
						array[i] = c;
						break;
					}
				}
			}
		}

		for (char c : array) {
			full.add(c);
		}
		return new Charset(full);
	}

	public boolean scanForPossibilities(String text, String word,
			Map<Character, Character> transed) {
		boolean found = false;
		List<String> ngrams = u.ngramize(text, word.length())
				.get(word.length());
		StringBuilder b = new StringBuilder(word.length());
		for (int i = 0; i < word.length(); i++) {
			if (transed.containsKey(word.charAt(i))) {
				b.append(word.charAt(i));
			} else {
				b.append(".");
			}
		}
		for (String s : ngrams) {
			if (s.matches(b.toString())) {
				found = true;
				break;
			}
		}
		return found;
	}

	
	
}
